import axios from 'axios'
import { ElMessage, ElNotification } from 'element-plus'

const ResponseState = {
  success: 200, //得到正确响应
}

let timesArr = []
const fn_msgFirstTime = (name, duration = 2000) => {
  if (timesArr.includes(name)) return false
  timesArr.push(name)
  setTimeout(() => {
    timesArr = []
  }, duration)
  return true
}
// 创建axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL + '/a/api',
  timeout: 15000,
})

// http请求拦截器
service.interceptors.request.use(
  config => {
    config.headers.Authorization = window.localStorage.getItem('token')
    return config
  },
  error => {
    ElMessage.error('请求超时')
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.status !== ResponseState.success) {
      ElNotification({
        title: '系统异常',
        message: res.message,
        type: 'error',
      })

      return Promise.reject(res)
    }
    return res
  },
  error => {
    if (!error.response) {
      if (fn_msgFirstTime('network')) {
        ElMessage({
          message: '请求超时，请检查网络',
          type: 'error',
          duration: 3,
        })
      }
      return Promise.reject(error)
    }
    if (fn_msgFirstTime('error')) {
      ElNotification({
        title: '服务出现异常',
        message: error.message,
        type: 'error',
      })
    }
    return Promise.reject(error)
  }
)

export default service
